import "./reset.css";
import dayjs from "dayjs";
import editForm from "../form/index.vue";
import { zxcvbn } from "@zxcvbn-ts/core";
import { message } from "@/utils/message";
import userAvatar from "@/assets/user.jpg";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import ReCropperPreview from "@/components/ReCropperPreview";
import type { FormItemProps } from "../utils/types";
import uploadForm from "../form/uploadForm.vue";
import {
  getKeyList,
  isAllEmpty,
  hideTextAtIndex,
  deviceDetection
} from "@pureadmin/utils";
import { assertResponse } from "@/api/utils";
import {
  getPageList,
  addUser,
  updateUser,
  updateUserStatus,
  delUserById,
  resetPassword,
  uploadAvatar,
  exportUserInfoExcel
} from "@/api/system/user";
import { getRoleOption } from "@/api/system/role";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElProgress,
  ElMessageBox
} from "element-plus";
import { type Ref, h, ref, watch, computed, reactive, onMounted } from "vue";
import { CommonUtils } from "@/utils/common";

export function useUser(tableRef: Ref) {
  const form = reactive({
    username: "",
    mobile: "",
    status: null
  });
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  // 上传头像信息
  const avatarInfo = ref();
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const treeData = ref([]);
  const selectedNum = ref(0);
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "用户编号",
      prop: "id",
      width: 90
    },
    {
      label: "用户头像",
      prop: "avatar",
      cellRenderer: ({ row }) => (
        <el-image
          fit="cover"
          preview-teleported={true}
          src={row.avatar || userAvatar}
          preview-src-list={Array.of(row.avatar || userAvatar)}
          class="w-[24px] h-[24px] rounded-full align-middle"
        />
      ),
      width: 90
    },
    {
      label: "用户名称",
      prop: "username",
      minWidth: 130
    },
    {
      label: "用户昵称",
      prop: "nickname",
      minWidth: 130
    },
    {
      label: "性别",
      prop: "gender",
      minWidth: 90,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.gender === 0 ? "danger" : null}
          effect="plain"
        >
          {row.gender === 0 ? "女" : "男"}
        </el-tag>
      )
    },
    {
      label: "手机号码",
      prop: "mobile",
      minWidth: 90,
      formatter: ({ mobile }) => hideTextAtIndex(mobile, { start: 3, end: 6 })
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          beforeChange={() => beforeChange(scope.row)}
        />
      )
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "createTime",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });
  const pwdProgress = [
    { color: "#e74242", text: "非常弱" },
    { color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  // 当前密码强度（0-4）
  const curScore = ref();
  const roleOptions = ref([]);
  const beforeChange = (row: any) => {
    return new Promise((resolve, reject) => {
      ElMessageBox.confirm(
        `确认要${!row.status ? "启用" : "停用"}用户${row.username}吗？`,
        "系统提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          updateUserStatus({ id: row.id, status: row.status ? 1 : 0 })
            .then(res => assertResponse(res, `修改用户${row.username}状态失败`))
            .then(() => {
              message("已成功修改用户状态", { type: "success" });
              resolve(true);
            })
            .catch(() => reject(false));
        })
        .catch(() => reject(false)); // 用户取消
    });
  };

  function handleDelete(row) {
    delUserByIds(row.id.toString());
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const ids = getKeyList(curSelected, "id");
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    delUserByIds(ids);
  }
  async function delUserByIds(ids: Array<number>) {
    await delUserById(ids)
      .then(res => {
        assertResponse(res, `编号为「${ids}」的用户删除失败`).then(() => {
          message(`已删除用户编号为「${ids}」的数据`, {
            type: "success"
          });
          onSearch();
        });
      })
      .finally(() => {
        tableRef.value.getTableRef().clearSelection();
      });
  }

  async function onSearch() {
    loading.value = true;
    await getPageList({
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize,
      username: form.username,
      status: form.status,
      mobile: form.mobile
    })
      .then(res =>
        assertResponse(res, "获取用户失败").then(data => {
          (dataList.value = data.list), (pagination.total = data.total);
        })
      )
      .finally(() => {
        loading.value = false;
      });
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}用户`,
      props: {
        formInline: {
          title,
          id: row?.id ?? "",
          nickname: row?.nickname ?? "",
          username: row?.username ?? "",
          mobile: row?.mobile ?? undefined,
          email: row?.email ?? undefined,
          gender: row?.gender ?? 1,
          status: row?.status ?? 1,
          roleId: row?.roleId ?? 4,
          remark: row?.remark ?? undefined
        },
        roleOptions: roleOptions
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了用户名称为「${curData.username}」的这条数据`, {
            type: "success"
          });
        }
        FormRef.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            const request =
              title === "新增"
                ? addUser(curData)
                : updateUser(curData.id, curData);
            request
              .then(res => assertResponse(res, `${title}用户失败`))
              .then(() => {
                chores();
                onSearch();
              })
              .finally(() => {
                done(); // 无论成功失败都关闭弹框
              });
          }
        });
      }
    });
  }
  async function exportAllExcel() {
    const fileName = "用户列表.xls";
    const params = { fileName };
    exportUserInfoExcel(fileName, params);
  }
  const cropRef = ref();

  /** 上传头像 */
  function handleUpload(row) {
    addDialog({
      title: "裁剪、上传头像",
      width: "40%",
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () =>
        h(ReCropperPreview, {
          ref: cropRef,
          imgSrc: row.avatar || userAvatar,
          onCropper: info => (avatarInfo.value = info)
        }),
      beforeSure: done => {
        // 将Base64编码转换为Blob
        const blob = CommonUtils.base64ToBlob(
          avatarInfo.value.base64,
          avatarInfo.value.blob.type
        );
        const fileName = `avatar_${Date.now()}.png`;
        const file = new File([blob], fileName, {
          type: blob.type,
          lastModified: Date.now()
        });
        uploadAvatar(row.id, file)
          .then(res => assertResponse(res, "上传图片失败"))
          .then(() => {
            message("上传图片成功", { type: "success" });
            // 刷新表格数据
            onSearch();
          })
          .finally(() => {
            done(); // 关闭弹框
          });
      },
      closeCallBack: () => cropRef.value.hidePopover()
    });
  }

  watch(
    pwdForm,
    ({ newPwd }) =>
      (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  );

  /** 重置密码 */
  function handleReset(row) {
    addDialog({
      title: `重置 ${row.username} 用户的密码`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <>
          <ElForm ref={ruleFormRef} model={pwdForm}>
            <ElFormItem
              prop="newPwd"
              rules={[
                {
                  required: true,
                  message: "请输入新密码",
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={pwdForm.newPwd}
                placeholder="请输入新密码"
              />
            </ElFormItem>
          </ElForm>
          <div class="mt-4 flex">
            {pwdProgress.map(({ color, text }, idx) => (
              <div
                class="w-[19vw]"
                style={{ marginLeft: idx !== 0 ? "4px" : 0 }}
              >
                <ElProgress
                  striped
                  striped-flow
                  duration={curScore.value === idx ? 6 : 0}
                  percentage={curScore.value >= idx ? 100 : 0}
                  color={color}
                  stroke-width={10}
                  show-text={false}
                />
                <p
                  class="text-center"
                  style={{ color: curScore.value === idx ? color : "" }}
                >
                  {text}
                </p>
              </div>
            ))}
          </div>
        </>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: done => {
        ruleFormRef.value.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            resetPassword({
              id: row.id,
              password: pwdForm.newPwd
            })
              .then(res =>
                assertResponse(res, `重置「${row.username}」用户密码失败`).then(
                  () => {
                    message(`已成功重置「${row.username}」用户的密码`, {
                      type: "success"
                    });
                    onSearch(); // 刷新表格数据
                  }
                )
              )
              .finally(() => {
                done(); // 关闭弹框
              });
          }
        });
      }
    });
  }

  async function openUploadDialog() {
    const uploadFormRef = ref();
    addDialog({
      title: `导入用户`,
      props: {},
      width: "30%",
      closeOnClickModal: false,
      contentRenderer: () => h(uploadForm, { ref: uploadFormRef }),
      beforeSure: done => {
        console.log("上传文件");
        // uploadFormRef.value.getFormRef().submit();
        // done();
        // onSearch();
      }
    });
  }
  onMounted(async () => {
    onSearch();
    // 角色列表
    roleOptions.value = await getRoleOption();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleDelete,
    handleUpload,
    handleReset,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    exportAllExcel,
    openUploadDialog
  };
}
